<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-hk">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="命名和函数
对象和数据结构">
<meta property="og:type" content="article">
<meta property="og:title" content="代码整洁之道摘要">
<meta property="og:url" content="http://jocens.oschina.io/blog/2017/04/05/CleanCode/index.html">
<meta property="og:site_name" content="Averson">
<meta property="og:description" content="命名和函数
对象和数据结构">
<meta property="og:updated_time" content="2017-04-08T06:28:25.213Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="代码整洁之道摘要">
<meta name="twitter:description" content="命名和函数
对象和数据结构">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://jocens.oschina.io/blog/2017/04/05/CleanCode/"/>





  <title> 代码整洁之道摘要 | Averson </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-hk">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/blog/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Averson</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle"></p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首頁
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            歸檔
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            標籤
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://jocens.oschina.io/blog/blog/2017/04/05/CleanCode/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Averson">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/blog/images/avatar.gif">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="Averson">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="Averson" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                代码整洁之道摘要
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">發表於</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-04-05T19:00:50+08:00">
                2017-04-05
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2017/04/05/CleanCode/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2017/04/05/CleanCode/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <ul>
<li>命名和函数</li>
<li>对象和数据结构</li>
</ul>
<a id="more"></a>
<h2 id="命名和函数"><a href="#命名和函数" class="headerlink" title="命名和函数"></a>命名和函数</h2><h3 id="让行为更明确"><a href="#让行为更明确" class="headerlink" title="让行为更明确"></a>让行为更明确</h3><ul>
<li>它是什么类型的东西</li>
<li>访问它的条件应该有意义</li>
<li>修改它应该赋予有意义的东西</li>
<li>结果能让人明确的使用？</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> List&lt;<span class="keyword">int</span>[]&gt; getThem() &#123;</div><div class="line">  <span class="comment">// list1 是什么东西</span></div><div class="line">  List&lt;<span class="keyword">int</span>[]&gt; list1 = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">  <span class="keyword">for</span> (<span class="keyword">int</span>[] x : theList) &#123;</div><div class="line">    <span class="comment">// x[0] 是什么, 4 表示什么.</span></div><div class="line">    <span class="keyword">if</span> (x[<span class="number">0</span>] == <span class="number">4</span>) &#123;</div><div class="line">      list1.add(x);</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">  <span class="comment">// 返回的结果如何用?</span></div><div class="line">  <span class="keyword">return</span> list1;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>本意是：</p>
<ul>
<li>int[] 表示单元格信息</li>
<li>theList 表示所有的单元格</li>
<li>0 下标表示状态</li>
<li>4 表示已经标记过了</li>
<li>list1 表示一个标记过单元格的结果集合</li>
<li>getThem() 表示这个行为能获得所有标记过的单元格集合</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> List&lt;<span class="keyword">int</span>[]&gt; getFlaggedCells() &#123;</div><div class="line">  List&lt;<span class="keyword">int</span>[]&gt; flaggedCells = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">  <span class="keyword">for</span> (<span class="keyword">int</span>[] cell : gameBoard) &#123;</div><div class="line">    <span class="keyword">if</span> (cell[STATUS_INDEX] == FLAGGED) &#123;</div><div class="line">      flaggedCells.add(cell);</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">  <span class="keyword">return</span> flaggedCells;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>但是单元格类型还不是一眼就能看出，将其封装成 Cell 更加直观和简洁。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 我们知道了返回的是带有 Flagged 的所有扫雷盘中的格子</span></div><div class="line"><span class="function"><span class="keyword">public</span> List&lt;Cell&gt; <span class="title">getFlaggedCells</span><span class="params">()</span> </span>&#123;</div><div class="line">  List&lt;Cell&gt; flaggedCells = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">  <span class="keyword">return</span> flaggedCells;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 在扫雷盘上筛选出已经标记过的 cell 并且添加到返回结果集中</span></div><div class="line"><span class="keyword">for</span> (Cell cell : gameBoard) &#123;</div><div class="line">  <span class="keyword">if</span> (cell.isFlagged()) &#123;</div><div class="line">    flaggedCells.add(cell);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> List&lt;Cell&gt; <span class="title">getFlaggedCells</span><span class="params">()</span> </span>&#123;</div><div class="line">  List&lt;Cell&gt; flaggedCells = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">  <span class="keyword">for</span> (Cell cell : gameBoard) &#123;</div><div class="line">    <span class="keyword">if</span> (cell.isFlagged()) &#123;</div><div class="line">      flaggedCells.add(cell);</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">  <span class="keyword">return</span> flaggedCells;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="让区分更加明确"><a href="#让区分更加明确" class="headerlink" title="让区分更加明确"></a>让区分更加明确</h3><p>到底谁是被移动的文件，谁是移动的文件。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">move</span><span class="params">(File file1, File file1)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>改善：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">move</span><span class="params">(File from, File to)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="方法名"><a href="#方法名" class="headerlink" title="方法名"></a>方法名</h3><p>静态工厂代替构造器，这个可以参考 Effect Java 的第二章。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">Complex fulcrumPoint = <span class="keyword">new</span> Complex(<span class="number">23.0</span>);</div><div class="line"></div><div class="line"><span class="comment">// static factory</span></div><div class="line">Complex fulcrumPoint = Complex.fromRealNumber(<span class="number">23.0</span>);</div></pre></td></tr></table></figure>
<h3 id="一元函数"><a href="#一元函数" class="headerlink" title="一元函数"></a>一元函数</h3><p>事件：有输入参数无输出参数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">void</span> <span class="title">passwordAttemptFailedTimes</span><span class="params">(<span class="keyword">int</span> attempts)</span></span>;</div></pre></td></tr></table></figure>
<p>如果函数要对输入参数进行转换，应该体现在返回值上。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function">InputStream <span class="title">openFile</span><span class="params">(String filename)</span></span>;</div></pre></td></tr></table></figure>
<h3 id="标识参数"><a href="#标识参数" class="headerlink" title="标识参数"></a>标识参数</h3><p>参数传入 <code>boolean</code> 值，如果 true 做一件事情，如果 false 做另外一件事情，这是非常丑陋的代码。</p>
<h3 id="二元函数"><a href="#二元函数" class="headerlink" title="二元函数"></a>二元函数</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">writeField(name);</div><div class="line">writeField(outputStream, name);</div><div class="line"></div><div class="line"><span class="comment">// 如果可以第二个函数应该变成这样:</span></div><div class="line">outputStream.writeFiled();</div><div class="line"><span class="comment">// or</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">FieldWriter</span> </span>&#123;</div><div class="line">  OutputStream os;</div><div class="line"></div><div class="line">  FieldHelper(OutputStream o) &#123;</div><div class="line">    os = o;</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">void</span> <span class="title">write</span><span class="params">(name)</span> </span>&#123;</div><div class="line">    o.write(name);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>显然第一个函数更加直观，写入一个属性，第二个多少会停顿一下，往指定输出流写入一个属性。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Point point = <span class="keyword">new</span> Point(<span class="number">0</span>, <span class="number">0</span>);</div></pre></td></tr></table></figure>
<p>这个二元参数就非常的自然，因为现实存在中表达一个点应该有 x, y 两个坐标。</p>
<h3 id="多参数"><a href="#多参数" class="headerlink" title="多参数"></a>多参数</h3><p>指代包括或超过三个参数以上的行为成为多参数。这个时候应该考虑一下多个参数是否应该封装为一个对象了。如下。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="function">Circle <span class="title">makeCircle</span><span class="params">(<span class="keyword">double</span> x, <span class="keyword">double</span> y, <span class="keyword">double</span> radius)</span></span>;</div><div class="line"><span class="function">Circle <span class="title">makeCircle</span><span class="params">(Point center, <span class="keyword">double</span> radius)</span></span>;</div></pre></td></tr></table></figure>
<h3 id="副作用"><a href="#副作用" class="headerlink" title="副作用"></a>副作用</h3><p>函数不要对类中的变量做出未能预期的改动。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserValidator</span> </span>&#123;</div><div class="line">  <span class="keyword">private</span> Cryptographer cryptographer;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">checkPassword</span><span class="params">(String username, String password)</span> </span>&#123;</div><div class="line">    User user = UserRepository.findByName(username);</div><div class="line">    <span class="keyword">if</span> (user != User.NULL) &#123;</div><div class="line">      String codedPhrase = user.getPhraseEncodeByPassword();</div><div class="line">      String phrase = cryptographer.decrypt(codedPhrase, password);</div><div class="line">      <span class="keyword">if</span> (<span class="string">"valid password"</span>.equals(phrase)) &#123;</div><div class="line">        <span class="comment">// 副作用 (side effect)</span></div><div class="line">        <span class="comment">// 要的是检查密码，不应该在里面清楚会话，所以已经登录的人再度检查的时候，就会出现会话被初始化的风险。</span></div><div class="line">        Session.initialize();</div><div class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">      &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Session.initialize();</div></pre></td></tr></table></figure>
<p>这句代码会导致一次时序性的偶尔，也就是说 <code>checkPassword</code> 只能在特定的时间点（初始化会话是安全的时候）调用。</p>
<p><strong>输出参数</strong>问题</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">appendFooter(s);</div></pre></td></tr></table></figure>
<p>把 s 添加到什么的后面，到底是什么？于是你要看方法签名，这样思路就被打断了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">appendFooter</span><span class="params">(StringBuffer report)</span></span>;</div></pre></td></tr></table></figure>
<p>应该改成：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">report.appendFooter();</div></pre></td></tr></table></figure>
<p>总而言之，应该避免使用输出参数。如果函数必须修改某种状态，就修改所属对象的状态。</p>
<h3 id="区分指令和询问"><a href="#区分指令和询问" class="headerlink" title="区分指令和询问"></a>区分指令和询问</h3><p>函数要么修改对象的状态，要么返回对象的相关信息。不应该混淆。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">set</span><span class="params">(String attribute, String value)</span></span>;</div></pre></td></tr></table></figure>
<p>设置某个属性的值，如果成功返回 true 如果不存在属性返回 false。这回导致如下语句。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span>(set(<span class="string">"username"</span>, <span class="string">"Averson"</span>)) &#123;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>那么你会考虑这个 if 判断中 set 行为依据什么来判断你接下来的步骤？</p>
<p>一个通过会思考的东西，set 返回 false 的是 username 属性的值不是 “Averson” 值呢？还是 username 属性不存在？</p>
<p>所以你应该区分开来分段的写</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span>(attributeExists(<span class="string">"username"</span>)) &#123;</div><div class="line">  setAttribute(<span class="string">"username"</span>, <span class="string">"Averson"</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="使用异常代替错误码"><a href="#使用异常代替错误码" class="headerlink" title="使用异常代替错误码"></a>使用异常代替错误码</h3><p>错误码默认是可以忽略的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (deleteDeprecatedLog() == OK) &#123;</div><div class="line">  <span class="keyword">if</span> (delete... == OK) &#123;</div><div class="line"></div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>显然这里没有处理 ERROR 的状态，就这样被忽略了，实际错误码的设置就是应该让调用者发现错误马上处理。其次，这样的话函数的执行如果在处理错误方面更侧重的话，就违背了函数只做一件事的原则了，上述的 <code>deleteDeprecatedLog()</code> 本应该偏向于删除日志的操作，错误处理我们应该单独分离出来。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">()</span> </span>&#123;</div><div class="line">  <span class="keyword">try</span> &#123;</div><div class="line">    deleteDeprecatedLog();</div><div class="line">    delete...();</div><div class="line">  &#125; <span class="keyword">catch</span>(LogException e) &#123;</div><div class="line">    handleException(e);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>另外还有错误码无法跨域，必须逐层向上转发。</p>
<p>看个例子</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> OK = <span class="keyword">true</span>;</div><div class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> ERROR = <span class="keyword">false</span>;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    CacheHelper.deleteSystemCache();</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">CacheHelper</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">deleteSystemCache</span><span class="params">()</span> </span>&#123;</div><div class="line">      <span class="keyword">if</span> (deleteDeprecatedLogCache() == OK) &#123;</div><div class="line">        <span class="comment">// do something...</span></div><div class="line">        <span class="keyword">if</span> (deleteImageCache() == OK) &#123;</div><div class="line">          <span class="comment">// do something...</span></div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">          <span class="comment">// error handle</span></div><div class="line">        &#125;</div><div class="line">      &#125; <span class="keyword">else</span> &#123;</div><div class="line">        <span class="comment">// error handle</span></div><div class="line">      &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">deleteDeprecatedLogCache</span><span class="params">()</span> </span>&#123;</div><div class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">deleteImageCache</span><span class="params">()</span> </span>&#123;</div><div class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    CacheHelper.deleteSystemCache();</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">CacheHelper</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">deleteSystemCache</span><span class="params">()</span> </span>&#123;</div><div class="line">      <span class="keyword">try</span> &#123;</div><div class="line">        deleteDeprecatedLogCache();</div><div class="line">        deleteImageCache();</div><div class="line">      &#125; <span class="keyword">catch</span> (CacheException e) &#123;</div><div class="line">        <span class="comment">// 如果上级可以处理或者能做有意义的处理, 我们可以继续往上抛出.</span></div><div class="line">        ExceptionService.processException(e);</div><div class="line">      &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">deleteDeprecatedLogCache</span><span class="params">()</span> <span class="keyword">throws</span> CacheException </span>&#123;</div><div class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> CacheException(<span class="string">"delete deprecated cache error"</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">deleteImageCache</span><span class="params">()</span> <span class="keyword">throws</span> CacheException </span>&#123;</div><div class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> CacheException(<span class="string">"delete image cache error"</span>);</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line"></div><div class="line"></div><div class="line">  <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">CacheException</span> <span class="keyword">extends</span> <span class="title">Exception</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CacheException</span><span class="params">()</span> </span>&#123;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CacheException</span><span class="params">(String message)</span> </span>&#123;</div><div class="line">      <span class="keyword">super</span>(message);</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>当然在你抛出异常的情况下也应该考虑抛出是否合理。因为异常的抛出会增加强制调用者做额外的处理，增加负担，所以异常的抛出考虑两种情况：</p>
<ul>
<li>如果调用者可以恢复此异常情况，可以考虑抛出。</li>
<li>如果调用者不能恢复，但能做出有意义的事，如记录处理。</li>
</ul>
<p>另外异常的抛出应该尽可能包含多的提供给调用者修复的信息。</p>
<h2 id="对象和数据结构"><a href="#对象和数据结构" class="headerlink" title="对象和数据结构"></a>对象和数据结构</h2><p>面向过程还是面向对象？</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Java/" rel="tag"># Java</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2017/04/03/Handler/" rel="next" title="Handler 机制">
                <i class="fa fa-chevron-left"></i> Handler 机制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2017/04/05/CleanCode/"
           data-title="代码整洁之道摘要" data-url="http://jocens.oschina.io/blog/blog/2017/04/05/CleanCode/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目錄
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            本站概覽
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.gif"
               alt="Averson" />
          <p class="site-author-name" itemprop="name">Averson</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">文章</span>
              </a>
            </div>
          

          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">標籤</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#命名和函数"><span class="nav-number">1.</span> <span class="nav-text">命名和函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#让行为更明确"><span class="nav-number">1.1.</span> <span class="nav-text">让行为更明确</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#让区分更加明确"><span class="nav-number">1.2.</span> <span class="nav-text">让区分更加明确</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法名"><span class="nav-number">1.3.</span> <span class="nav-text">方法名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一元函数"><span class="nav-number">1.4.</span> <span class="nav-text">一元函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#标识参数"><span class="nav-number">1.5.</span> <span class="nav-text">标识参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二元函数"><span class="nav-number">1.6.</span> <span class="nav-text">二元函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多参数"><span class="nav-number">1.7.</span> <span class="nav-text">多参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#副作用"><span class="nav-number">1.8.</span> <span class="nav-text">副作用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#区分指令和询问"><span class="nav-number">1.9.</span> <span class="nav-text">区分指令和询问</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用异常代替错误码"><span class="nav-number">1.10.</span> <span class="nav-text">使用异常代替错误码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#对象和数据结构"><span class="nav-number">2.</span> <span class="nav-text">对象和数据结构</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Averson</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 強力驅動
</div>

<div class="theme-info">
  主題 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"averson"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/blog/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/blog/js/src/hook-duoshuo.js"></script>
  













  
  

  

  

  

  


</body>
</html>
